package rewardsonline.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
	
	@Override
	protected void configure(HttpSecurity http) throws Exception {
		
		http.csrf().disable();
		
		http
	        .authorizeRequests()
	        	.antMatchers("/styles/**", "/images/**", "/logout", "/login", "/denied", "/home", "/").permitAll()
	        	.antMatchers("/rewards/newReward").access("hasRole('ROLE_ADMIN')")
	        	.antMatchers(HttpMethod.POST, "/accounts/*").access("hasRole('ROLE_ADMIN')")
	        	.antMatchers("/**").access("hasAnyRole('ROLE_USER','ROLE_ADMIN')")
	        	.and()
	        .formLogin()
	            .permitAll()
	            .failureUrl("/login?login_error=1")
	            .and()
	        .logout()
	        	.logoutSuccessUrl("/home")
	            .permitAll()
	            .and()
	        .exceptionHandling().accessDeniedPage("/denied");
	}
	
	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		
		auth.inMemoryAuthentication()
				.withUser("joe").password("spring").roles("USER").and()
				.withUser("vince").password("vince").roles("USER").and()
				.withUser("edith").password("edith").roles("ADMIN").and()
				.withUser("admin").password("spring").roles("ADMIN");
	}
}
